package file;

import event.EventBase;
import event.EventEnum;
import event.EventSystem;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ServerListFile {
    private static ServerListFile instance;

    private ServerListFile() {

    }

    public static ServerListFile instance() {
        if (instance == null) {
            instance = new ServerListFile();
        }
        return instance;
    }

    public void save(String content) {
        final String path = PathHelper.getServerListFilePath();
        File file = new File(path);

        if (file.exists()) {
            file.delete();
        }

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");

            outputStreamWriter.write(content);

            outputStreamWriter.flush();
            outputStreamWriter.close();

            EventSystem.instance().dispatch(new EventBase(EventEnum.serverListFileRefresh, null));
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    public String read() {
        String result = "";
        try {
            File file = new File(PathHelper.getServerListFilePath());
            if (file.exists()) {
                Path path = Paths.get(PathHelper.getServerListFilePath());
                List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
                int i = 0;
                for (; i < lines.size() - 1; ++i) {
                    result += lines.get(i);
                    result += System.lineSeparator();
                }
                result += lines.get(i);
            }
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
        return result;
    }

}
